package com.jswlw.controller.devapi.adapter;

import com.alibaba.fastjson.JSON;
import com.jswlw.controller.devapi.req.*;
import com.jswlw.controller.devapi.resp.IdResponse;
import com.jswlw.entity.biz.*;
import com.jswlw.entity.biz.log.*;
import com.jswlw.service.biz.*;
import com.jswlw.service.biz.log.*;
import com.jswlw.service.helper.CmdType;
import com.jswlw.service.helper.DevApiHelper;
import com.jswlw.service.helper.HttpHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Slf4j
@Component
public class DevApiAdapter {
    @Autowired
    DevInfoService devInfoService;
    @Autowired
    IdCreatorService idCreatorService;
    @Autowired
    LogHeartService logHeartService;
    @Autowired
    LogSyncWorkStatusService logSyncWorkStatusService;
    @Autowired
    LogSyncDayService logSyncDayService;
    @Autowired
    LogSyncWaterService logSyncWaterService;
    @Autowired
    DevFilterService devFilterService;
    @Autowired
    ImeiIcCidService imeiIcCidService;
    @Autowired
    BindRecordService bindRecordService;
    @Autowired
    LogDevOptService logDevOptService;
    @Autowired
    HttpHelper httpHelper;
    @Autowired
    ApiFailService apiFailService;
    @Autowired
    DevApiHelper devApiHelper;

    public IdResponse createId(GainDeviceIdMessage message) {
        IdResponse response = new IdResponse();
        DevInfo devInfo = devInfoService.find4Imei(message.getImei());
        if (Objects.nonNull(devInfo)) {
            response.setData(IdResponse.IdData.builder().id(devInfo.getId()).iccid(message.getImei()).build());
        } else {
            //生成ID
            int id = idCreatorService.fetch();
            //插入设备信息
            devInfo = DevInfo.fill();
            devInfo.setId(String.valueOf(id));
            devInfo.setImei(message.getImei());
            devInfoService.add(devInfo);
            response.setData(IdResponse.IdData.builder().id(String.valueOf(id)).iccid(message.getImei()).build());
        }
        response.success();
        return response;
    }

    @Value("${dev.api.url.bindPricing}")
    String bindPricing;

    public void heartbeat(HeartbeatMessage message) {
        log.info("接收心跳数据:" + JSON.toJSONString(message));
        LogHeart logHeart = new LogHeart();
        BeanUtils.copyProperties(message, logHeart);
        logHeart.setRes(JSON.toJSONString(message));
        logHeart.setImei(message.getImei());
        logHeart.setCreateTime(System.currentTimeMillis());
        logHeartService.add(logHeart);

        String imei = message.getImei();
        final DevInfo devInfo = devInfoService.find4Imei(imei);
        boolean insert = false;
        devInfo.setDevStatus(message.getSbzt());
        devInfo.setRemainFlow(message.getSyll());
        devInfo.setRemainTime(message.getSyts());
        devInfo.setUsedFlow(message.getYyll());
        devInfo.setUsedTime(message.getYyts());
        devInfo.setRawTds(message.getJstds());
        devInfo.setPurityTds(message.getYstds());
        devInfo.setAsignal(message.getXhqdz());
        devInfo.setScreenStatus(message.getPmzt());
        devInfo.setBillTypeId(message.getGzms());
        if (insert) {
            devInfoService.add(devInfo);
        } else {
            devInfoService.update(devInfo);
        }

        List<DevFilter> devFilters = devFilterService.find4DevId(devInfo.getId());
        if (!CollectionUtils.isEmpty(devFilters)) {
            for (int i = 0; i < devFilters.size(); i++) {
                DevFilter devFilter = devFilters.get(i);
                if (devFilter.getSort() == 1) {
                    devFilter.setUsed(message.getDyijlxzdz() - message.getDyijlxsyz());
                } else if (devFilter.getSort() == 2) {
                    devFilter.setUsed(message.getDerjlxzdz() - message.getDerjlxsyz());
                } else if (devFilter.getSort() == 3) {
                    devFilter.setUsed(message.getDsanjlxzdz() - message.getDsanjlxsyz());
                } else if (devFilter.getSort() == 4) {
                    devFilter.setUsed(message.getDsijlxzdz() - message.getDsijlxsyz());
                } else if (devFilter.getSort() == 5) {
                    devFilter.setUsed(message.getDwujlxzdz() - message.getDwujlxsyz());
                }
                devFilterService.update(devFilter);
            }
        }

        //下发时长信息
        ApiFail apiFail = new ApiFail();
        apiFail.setDevId(devInfo.getId());
        apiFail.setCmdType(Integer.valueOf(CmdType.SyncTime.getCmd()));
        List<ApiFail> list = apiFailService.queryList(apiFail);
        if (!CollectionUtils.isEmpty(list)) {
            log.error("下发同步时长信息:" + JSON.toJSONString(message));
            final int count = list.size();

            if (devApiHelper.sync_day(devInfo.getImei(), (short) (devInfo.getUsedTime() + count))) {
                list.forEach(af -> {
                    apiFailService.delete(af.getId());
                });
            }
        }

    }

    public void asyncWater(SyncWaterMessage message) {
        String imei = message.getImei();
        int useFlux = message.getWater();
        DevInfo devInfo = devInfoService.find4Imei(imei);
        devInfo.setUsedFlow(devInfo.getUsedFlow() + useFlux);
        devInfoService.update(devInfo);

        LogSyncWater logSyncWater = new LogSyncWater();
        BeanUtils.copyProperties(message, logSyncWater);
        logSyncWater.setRes(JSON.toJSONString(message));
        logSyncWater.setCreateTime(new Date());
        logSyncWater.setWater(Integer.valueOf(message.getWater()));
        logSyncWaterService.add(logSyncWater);

        //新增用水操作信息
        logDevOptService.add(LogDevOpt.builder()
                .res(message.getImei())
                .imei(message.getImei())
                .opt("用水:" + message.getWater() * 0.01)
                .createUserId(1)
                .createTime(new Date())
                .build());
    }

    public void asyncWorkStatus(SyncWorkStatusMessage message) {
        int status = message.getState();
        String imei = message.getImei();
        DevInfo devInfo = devInfoService.find4Imei(imei);
        devInfo.setDevStatus(status);
        devInfoService.update(devInfo);

        LogSyncWorkStatus logSyncWorkStatus = new LogSyncWorkStatus();
        BeanUtils.copyProperties(message, logSyncWorkStatus);
        logSyncWorkStatus.setRes(JSON.toJSONString(message));
        logSyncWorkStatus.setCreateTime(new Date());
        logSyncWorkStatusService.add(logSyncWorkStatus);
    }

    public void asyncDay(SyncDayMessage message) {
        int day = message.getDay();
        String imei = message.getImei();
        DevInfo devInfo = devInfoService.find4Imei(imei);
        devInfo.setUsedTime(devInfo.getUsedTime() + day);
        devInfoService.update(devInfo);

        LogSyncDay logSyncDay = new LogSyncDay();
        BeanUtils.copyProperties(message, logSyncDay);
        logSyncDay.setRes(JSON.toJSONString(message));
        logSyncDay.setCreateTime(new Date());
        logSyncDayService.add(logSyncDay);
    }

    public void updateIccid(ReadIccidFromDeviceMessage message) {
        ImeiIcCid imeiIcCid = new ImeiIcCid();
        imeiIcCid.setIcCid(message.getIccid());
        imeiIcCid.setImei(message.getImei());
        imeiIcCid.setCreateTime(new Date());
        DevInfo devInfo = devInfoService.find4Imei(message.getImei());
        if (Objects.nonNull(devInfo)) {
            imeiIcCid.setDevId(devInfo.getId());
        }
        imeiIcCidService.add(imeiIcCid);
    }
}
